<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>招生管理</el-breadcrumb-item>
      <el-breadcrumb-item>发布</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->


      <!-- 用户列表区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" width="50%"  border stripe >
        <el-form-item type="index"></el-form-item>
        <el-form-item label="标题" prop="title"><el-input v-model="addForm.title" style="width: 200px"></el-input></el-form-item>
        <el-form-item label="内容" prop="introduce"><el-input v-model="addForm.content" style="width: 600px"></el-input></el-form-item>
         <el-form-item>
           <div class="block">
             <span class="demonstration">默认</span>
             <el-date-picker
               v-model="addForm.startTime"
               type="date"
               placeholder="选择日期">
             </el-date-picker>
           </div>
         </el-form-item>
          <el-form-item>
            <div class="block">
              <span class="demonstration">默认</span>
              <el-date-picker
                v-model="addForm.endTime"
                type="date"
                placeholder="选择日期">
              </el-date-picker>
            </div>
          </el-form-item>

      </el-form>

      <el-form :model="dynamicValidateForm" ref="dynamicValidateForm" width="50%"  border stripe class="demo-dynamic">
        <el-form-item
          v-for="(domain, index) in dynamicValidateForm.domains"
          :label="'教学班' + index"
          :key="domain.key"
          :prop="'domains.' + index + '.value'"
        >
          <el-autocomplete
            v-model="domain.value"
            :fetch-suggestions="querySearchAsync"
            placeholder="请输入内容"
            @select="handleSelect"
            style="width: 100px"
          ></el-autocomplete>
          <el-button @click.prevent="removeDomain(domain)" style="margin-left: 10px">删除</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="addDomain">新增教学班</el-button>
          <el-button @click="resetForm('dynamicValidateForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>




    <el-row :gutter="20" >
      <el-col :span="4" >
        <el-button type="primary" @click="editUserInfo">发布</el-button>
      </el-col>
    </el-row>

  </div>
</template>

<script>
    export default {
        props: {
            defaultValue: {
                type: Object,
                default: () => {
                    return {
                        label: '',
                        value: '',
                        isLastItem: false
                    }
                }
            }
        },
        data() {

            return {
                restaurants: [],
                state: '',
                timeout:  null,
                dynamicValidateForm: {
                    domains: [{
                        value: ''
                    }],
                    email: ''
                },
                // 添加用户的表单数据
                addForm: {
                    title: '',
                    number: '',
                    content:'',
                    data:'',
                    class: '',
                    time: '',
                    introduce:'',
                    picture:'',
                },

            }
        },
        created() {
            this.getUserList()
            this.getTeacherList()
        },
        mounted() {
            this.restaurants = this.loadAll();
        },
        methods: {
            loadAll() {
                return [
                    { "value": "摸鱼" },
                    { "value": "划水" },
                    { "value": "偷懒" },
                    { "value": "睡觉" }
                ];
            },
            querySearchAsync(queryString, cb) {
                var restaurants = this.restaurants;
                var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;

                clearTimeout(this.timeout);
                this.timeout = setTimeout(() => {
                    cb(results);
                }, 3000 * Math.random());
            },
            createStateFilter(queryString) {
                return (state) => {
                    return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
                };
            },
            // 点击按钮，添加新用户
            addUser() {
                this.getTeacherList()
                this.$refs.addFormRef.validate(async valid => {
                    if (!valid) return
                    // 可以发起添加用户的网络请求
                    //         const { data: res } = await this.$http.post('users', this.addForm)
                    //
                    //         if (res.meta.status !== 201) {
                    //           this.$message.error('添加用户失败！')
                    //         }

                    this.$message.success('添加用户成功！')
                    // 隐藏添加用户的对话框
                    this.addDialogVisible = false
                    // 重新获取用户列表数据
                    this.getUserList()
                })
            },
            // 展示编辑用户的对话框
            async showEditDialog(id) {
                // const { data: res } = await this.$http.get('users/' + id)

                // if (res.meta.status !== 200) {
                //   return this.$message.error('查询用户信息失败！')
                // }

                // this.addForm = res.data
                this.editDialogVisible = true
            },
            // 监听修改用户对话框的关闭事件
            editDialogClosed() {
                this.$refs.addFormRef.resetFields()
            },
            // 修改用户信息并提交
            editUserInfo() {
                this.$refs.addFormRef.validate(async valid => {
                    if (!valid) return
                    // 发起修改用户信息的数据请求
                    // const {
                    //   data: res
                    // } = await this.$http.put(
                    //   'users/' + this.addForm.id, {
                    //     email: this.addForm.email,
                    //     mobile: this.addForm.mobile
                    //   }
                    // )

                    // if (res.meta.status !== 200) {
                    //   return this.$message.error('更新用户信息失败！')
                    // }

                    // 关闭对话框
                    this.editDialogVisible = false
                    // 刷新数据列表
                    this.getUserList()
                    // 提示修改成功
                    this.$message.success('发布招生简章成功！')
                })
            },
            // 根据Id删除对应的用户信息
            async removeUserById(id) {
                // 弹框询问用户是否删除数据
                const confirmResult = await this.$confirm(
                    '此操作将永久删除该用户, 是否继续?',
                    '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                ).catch(err => err)

                // 如果用户确认删除，则返回值为字符串 confirm
                // 如果用户取消了删除，则返回值为字符串 cancel
                // console.log(confirmResult)
                if (confirmResult !== 'confirm') {
                    return this.$message.info('已取消删除')
                }

                const {
                    data: res
                } = await this.$http.delete('users/' + id)

                if (res.meta.status !== 200) {
                    return this.$message.error('删除用户失败！')
                }

                this.$message.success('删除用户成功！')
                this.getUserList()
            },
            // 展示分配角色的对话框
            async setRole(userInfo) {
                this.userInfo = userInfo

                // 在展示对话框之前，获取所有角色的列表
                const {
                    data: res
                } = await this.$http.get('roles')
                if (res.meta.status !== 200) {
                    return this.$message.error('获取角色列表失败！')
                }

                this.rolesList = res.data

                this.setRoleDialogVisible = true
            },
            // 点击按钮，分配角色
            async saveRoleInfo() {
                if (!this.selectedRoleId) {
                    return this.$message.error('请选择要分配的角色！')
                }

                const {
                    data: res
                } = await this.$http.put(
                    `users/${this.userInfo.id}/role`, {
                        rid: this.selectedRoleId
                    }
                )

                if (res.meta.status !== 200) {
                    return this.$message.error('更新角色失败！')
                }

                this.$message.success('更新角色成功！')
                this.getUserList()
                this.setRoleDialogVisible = false
            },
            // 监听分配角色对话框的关闭事件
            setRoleDialogClosed() {
                this.selectedRoleId = ''
                this.userInfo = {}
            },
            handleRemove(file, fileList) {
                console.log(file, fileList)
            },
            handlePreview(file) {
                console.log(this.fileList)
                console.log(file.response)
            },
            handleExceed(files, fileList) {
                this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
            },
            beforeRemove(file, fileList) {
                console.log(fileList.slice(-3))
                return this.$confirm(`确定移除 ${file.name}？`)
            },
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        alert('submit!');
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
            removeDomain(item) {
                var index = this.dynamicValidateForm.domains.indexOf(item)
                if (index !== -1) {
                    this.dynamicValidateForm.domains.splice(index, 1)
                }
            },
            addDomain() {
                this.dynamicValidateForm.domains.push({
                    value: '',
                    key: Date.now()
                });
            }
        }
    }
</script>

<style lang="less" scoped>
  .el-col {
    margin-top: 30px;
    float:right;
  }
</style>
